/**   
* @Title: DateConvert.java
* @Package org.xaoyaoyao.cloud.jpa.utils
* @Description: TODO
* @author xaoyaoyao
* @date Feb 12, 2019 10:44:24 AM
* @version V1.0   
*/
package org.xaoyaoyao.cloud.jpa.utils;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.apache.commons.beanutils.Converter;

import lombok.extern.slf4j.Slf4j;

/**
 * @ClassName: DateConvert
 * @Description: TODO
 * @author xaoyaoyao
 * @date Feb 12, 2019 10:44:24 AM
 * 
 */
@Slf4j
public class DateConvert implements Converter {

	@Override
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public Object convert(Class clazz, Object value) {
		if (value == null) {
			return null;
		}
		if (value instanceof Date) {
			return value;
		}
		if (value instanceof Long) {
			Long longValue = (Long) value;
			return new Date(longValue.longValue());
		}
		if (value instanceof String) {
			String dateStr = (String) value;
			Date endTime = null;
			try {
				String regexp1 = "([0-9]{4})-([0-1][0-9])-([0-3][0-9])T([0-2][0-9]):([0-6][0-9]):([0-6][0-9])";
				String regexp2 = "([0-9]{4})-([0-1][0-9])-([0-3][0-9])(/t)([0-2][0-9]):([0-6][0-9]):([0-6][0-9])";
				String regexp3 = "([0-9]{4})-([0-1][0-9])-([0-3][0-9])";
				if (dateStr.matches(regexp1)) {
					dateStr = dateStr.split("T")[0] + " " + dateStr.split("T")[1];
					DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
					endTime = sdf.parse(dateStr);
					return endTime;
				} else if (dateStr.matches(regexp2)) {
					DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
					endTime = sdf.parse(dateStr);
					return endTime;
				} else if (dateStr.matches(regexp3)) {
					DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
					endTime = sdf.parse(dateStr);
					return endTime;
				} else {
					return dateStr;
				}
			} catch (ParseException e) {
				log.error(e.getMessage(), e);
			}
		}
		return value;
	}
}
